package com.salton123.imagepicker;

import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;

import androidx.fragment.app.FragmentActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.CursorLoader;
import androidx.loader.content.Loader;

import com.salton123.imagepciker.R;
import com.salton123.imagepicker.bean.ImageFolder;
import com.salton123.imagepicker.bean.ImageItem;
import com.salton123.imagepicker.custom.ImagePickerTextRepository;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * ================================================
 * 作    者：jeasonlzy（廖子尧 Github地址：https://github.com/jeasonlzy0216
 * 版    本：1.0
 * 创建日期：2016/5/19
 * 描    述：加载手机视频实现类
 * 修订历史：
 * ================================================
 */
public class VideoDataSource implements LoaderManager.LoaderCallbacks<Cursor> {

    public static final int VIDEO = 2;         //加载所有视频
    private static final String[] VIDEO_PROJECTION = {     //查询视频需要的数据列
            MediaStore.Video.Media.DISPLAY_NAME,   //视频的显示名称  aaa.mp4
            MediaStore.Video.Media.DATA,           //视频的真实路径  /storage/emulated/0/pp/downloader/wallpaper/aaa.mp4
            MediaStore.Video.Media.SIZE,           //视频的大小，long型  132492
            MediaStore.Video.Media.WIDTH,          //视频的宽度，int型  1920
            MediaStore.Video.Media.HEIGHT,         //视频的高度，int型  1080
            MediaStore.Video.Media.MIME_TYPE,      //视频的类型     image/jpeg
            MediaStore.Video.Media.DATE_ADDED,     //视频被添加的时间，long型  1450518608
            MediaStore.Video.Media.DURATION};      //视频时长，long型  ms

    private FragmentActivity activity;
    private OnVideosLoadedListener loadedListener;                     //视频加载完成的回调接口
    private ArrayList<ImageFolder> videoFolders = new ArrayList<>();   //所有的视频文件夹
    private boolean hasLoad = false; //是否加载过

    /**
     * @param activity       用于初始化LoaderManager，需要兼容到2.3
     * @param loadedListener 视频加载完成的监听
     */
    public VideoDataSource(FragmentActivity activity, OnVideosLoadedListener loadedListener) {
        this.activity = activity;
        this.loadedListener = loadedListener;

        LoaderManager loaderManager = LoaderManager.getInstance(activity);
        loaderManager.initLoader(VIDEO, null, this); //加载所有的视频
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        CursorLoader cursorLoader = null;
        //扫描所有视频
        cursorLoader = new CursorLoader(activity, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION,
                null, null, VIDEO_PROJECTION[6] + " DESC");
        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if (hasLoad) { //避免在onStart的时候重复回调
            return;
        }
        hasLoad = true;
        videoFolders.clear();

        if (data != null) {
            ArrayList<ImageItem> allVideos = new ArrayList<>();   //所有图片的集合,不分文件夹
            ArrayList<ImageItem> images = new ArrayList<>();
            if (videoFolders.size() > 0) {
                images.addAll(videoFolders.get(0).images);
            }
            int startI = 0;
            int tSize = images.size();

            while (data.moveToNext()) {
                //查询数据
                String videoName = data.getString(data.getColumnIndexOrThrow(VIDEO_PROJECTION[0]));
                String videoPath = data.getString(data.getColumnIndexOrThrow(VIDEO_PROJECTION[1]));

                File file = new File(videoPath);
                if (!file.exists() || file.length() <= 0) {
                    continue;
                }

                long videoSize = data.getLong(data.getColumnIndexOrThrow(VIDEO_PROJECTION[2])) / 1024;
                int videoWidth = data.getInt(data.getColumnIndexOrThrow(VIDEO_PROJECTION[3]));
                int videoHeight = data.getInt(data.getColumnIndexOrThrow(VIDEO_PROJECTION[4]));
                String videoMimeType = data.getString(data.getColumnIndexOrThrow(VIDEO_PROJECTION[5]));
                long videoAddTime = data.getLong(data.getColumnIndexOrThrow(VIDEO_PROJECTION[6]));
                long videoDuration = data.getLong(data.getColumnIndexOrThrow(VIDEO_PROJECTION[7]));
                //封装实体
                ImageItem imageItem = new ImageItem();
                imageItem.name = videoName;
                imageItem.path = videoPath;
                imageItem.size = videoSize;
                imageItem.width = videoWidth;
                imageItem.height = videoHeight;
                imageItem.mimeType = videoMimeType;
                imageItem.addTime = videoAddTime;
                imageItem.duration = videoDuration;
                allVideos.add(imageItem);
                //将视频放到图片和视频中
                if (startI == tSize) {
                    if (tSize == 0) {
                        File imageFile = new File(videoPath);
                        File imageParentFile = imageFile.getParentFile();
                        ImageFolder imageFolder = new ImageFolder();
                        imageFolder.contentType = MediaStore.Images.Media.CONTENT_TYPE;
                        imageFolder.name = imageParentFile.getName();
                        imageFolder.path = imageParentFile.getAbsolutePath();
                        ArrayList<ImageItem> imageItems = new ArrayList<>();
                        imageItems.add(imageItem);
                        imageFolder.cover = imageItem;
                        imageFolder.images = imageItems;
                        videoFolders.add(imageFolder);
                        tSize = 1;
                        startI = 1;
                    } else {
                        videoFolders.get(0).images.add(imageItem);
                    }
                } else {
                    for (int i = startI; i < tSize; i++) {
                        ImageItem imgItem = images.get(i);
                        if (imgItem.addTime < videoAddTime) {
                            videoFolders.get(0).images.add(videoFolders.get(0).images.indexOf(imgItem), imageItem);
                            startI = i;
                            break;
                        } else if (i == tSize - 1) {
                            startI = tSize;
                            videoFolders.get(0).images.add(imageItem);
                        }
                    }
                }
            }
            //防止没有视频报异常
            if (data.getCount() > 0 && allVideos.size() > 0) {
                //构造所有视频的集合
                ImageFolder allImagesFolder = new ImageFolder();
                allImagesFolder.contentType = MediaStore.Video.Media.CONTENT_TYPE;
                if (!ImagePickerTextRepository.INSTANCE.getAllPictures().isEmpty()) {
                    allImagesFolder.name = ImagePickerTextRepository.INSTANCE.getAllPictures();
                } else {
                    allImagesFolder.name = activity.getResources().getString(R.string.ip_all_images);
                }
                allImagesFolder.path = "/";
                allImagesFolder.cover = allVideos.get(0);
                allImagesFolder.images = allVideos;
                videoFolders.add(0, allImagesFolder);
            }

            data.moveToFirst();
        }

        //回调接口，通知视频数据准备完成
        ImagePicker.getInstance().addImageFolders(videoFolders);
        loadedListener.onVideosLoaded(videoFolders);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        System.out.println("--------");
    }

    /**
     * 所有视频加载完成的回调接口
     */
    public interface OnVideosLoadedListener {
        void onVideosLoaded(List<ImageFolder> videoFolders);
    }
}
